import express from "express";
import bodyParser from "body-parser";
import db from "./db";
const path = require("path");

const app = express();
app.use(express.static(path.join(__dirname, "../../rproj/dist")));
// console.log(path.join(__dirname, "../../rproj/dist"));

app.use(bodyParser.json());
interface Todo {
  id: string;
  text: string;
  completed: boolean;
  ctime: number;
  mtime: number;
}

app.get("/api/todos", (req, res) => {
  db.all(
    "SELECT id, text, completed, add_time as ctime, modify_time as mtime FROM todos",
    (err, rows) => {
      if (err) {
        console.error(err);
        res.sendStatus(500);
      } else {
        // console.log(rows);
        res.send(rows);
      }
    }
  );
});
app.post("/api/todos", (req, res) => {
  const { id, text, completed, ctime, mtime } = req.body;
  // console.log(ctime, mtime);
  db.run(
    "INSERT INTO todos (id, text, completed, add_time, modify_time) VALUES (?, ?, ?, ?, ?)",
    [id, text, completed, ctime, mtime],
    (err) => {
      if (err) {
        console.error(err);
        res.sendStatus(500);
      } else {
        res.sendStatus(200);
      }
    }
  );
});

app.patch("/api/todos/:id", (req, res) => {
  const { id } = req.params;
  const { text, completed, mtime } = req.body;
  if (!text && completed === undefined) {
    res.status(400).send('Bad Request: "text" or "completed" is required');
    return;
  }
  const todo = db.get<Todo>("SELECT * FROM todos WHERE id = ?", id);
  if (!todo) {
    res.status(404).send(`Not Found: todo with id ${id} not found`);
    return;
  }
  try {
    const newTodo = {
      ...todo,
      text: text,
      completed: completed,
      mtime: mtime,
    };
    db.run(
      "UPDATE todos SET text = ?, completed = ? , modify_time = ? WHERE id = ?",
      [newTodo.text, newTodo.completed, newTodo.mtime, id]
    );
    res.json(newTodo);
  } catch (error) {
    console.log(error);
  }
});

app.delete("/api/todos/:id", (req, res) => {
  const { id } = req.params;
  try {
    db.run("DELETE FROM todos WHERE id = ?", id);
    res.sendStatus(204);
  } catch (error) {
    console.error(error);
  }
});

app.listen(3001, () => {
  console.log("Server is listening on port 3001");
});
